package io.renren.modules.manage.service.impl;

import io.renren.modules.manage.entity.ProductCategoryEntity;
import io.renren.modules.manage.service.ProductCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.manage.dao.ProductDao;
import io.renren.modules.manage.entity.ProductEntity;
import io.renren.modules.manage.service.ProductService;


@Service("productService")
@Slf4j
public class ProductServiceImpl extends ServiceImpl<ProductDao, ProductEntity> implements ProductService {
    @Autowired
    private ProductCategoryService productCategoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = params.get("key").toString();
        QueryWrapper<ProductEntity> queryWrapper = new QueryWrapper<>();
        if (key.length() > 0) {
            queryWrapper.like("name", key);
        }
        log.info("params:{}", params);
        IPage<ProductEntity> page = this.page(
                new Query<ProductEntity>().getPage(params),
                queryWrapper
        );

        List<ProductCategoryEntity> categoryEntities = productCategoryService.list();

        page.getRecords().forEach(productEntity -> {
            ProductCategoryEntity productCategoryEntity = categoryEntities
                    .stream()
                    .filter(categoryEntity -> categoryEntity.getId() == productEntity.getCategoryId())
                    .collect(Collectors.toList()).get(0);
            productEntity.setCategoryName(productCategoryEntity.getName());
        });
        return new PageUtils(page);
    }

}
